// 图片base64数据获取
export const photoCompress = (file: any, compressedOption:any, callback:any) => {
    let fileReader = new FileReader()
    fileReader.readAsDataURL(file)

    fileReader.onload = () => {
        let fileResult = fileReader.result
        canvasDataURL(fileResult, compressedOption, callback)
    }
}

// 图片渲染至画布 并获取指定质量图片
const canvasDataURL = (path:any, compressedOption:any, callback:any) => {
    let img = new Image()
    img.src = path
    img.onload = () => {
        // 设置压缩后图片规格
        let quality = compressedOption.quality
        let w = compressedOption.width || img.width

        // 判断只存在宽度时，根据比例设置高度
        let h = compressedOption.height || (compressedOption.width ? compressedOption.width / (img.width / img.height) : '') || img.height

        // 生成canvas
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')

        // 设置宽高并渲染图片
        canvas.width = w
        canvas.height = h
        if (ctx) {
            ctx.drawImage(img, 0, 0, w, h)
        }


        let base64 = canvas.toDataURL('image/jpeg', quality)
        // https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLCanvasElement/toDataURL

        // 回调函数返回base64的值
        callback(base64)
    }
}

// 图片转码处理
export const convertBase64UrlToFile:any = (urlData:any, filename:any) => {
    let arr = urlData.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]

    let bstr = atob(arr[1])
    // https://www.runoob.com/jsref/met-win-atob.html
    let n = bstr.length

    let u8arr = new Uint8Array(n)
    // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
        // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt
    }

    // return new Blob([u8arr], { type: mime })
    // https://developer.mozilla.org/zh-CN/docs/Web/API/Blob

    return new File([u8arr], filename, { type: mime })
    // https://developer.mozilla.org/zh-CN/docs/Web/API/File
}

